
<template>
  <div class="category-manager">
    <div class="header">
      <h1>分类管理</h1>
      <el-button type="primary" @click="openDialog()">添加顶级分类</el-button>
    </div>

    <el-tree
      :data="categoryTree"
      :props="{ label: 'name', children: 'children' }"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      v-loading="loading"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <el-button size="small" type="text" @click="openDialog(null, data)">添加子分类</el-button>
            <el-button size="small" type="text" @click="openDialog(data, null)">编辑</el-button>
            <el-button size="small" type="text" @click="handleDelete(data)">删除</el-button>
          </span>
        </div>
      </template>
    </el-tree>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getCategoryTree,
  createCategory,
  updateCategory,
  deleteCategory,
} from '@/api/modules/product'
import type { Category } from '@/types'

const loading = ref(false)
const categoryTree = ref<Category[]>([])
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

const form = reactive<Partial<Category>>({
  id: undefined,
  name: '',
  parentId: 0,
  sort: 0,
})

const rules: FormRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}

const isEdit = computed(() => !!form.id)
const dialogTitle = computed(() => {
  if (isEdit.value) return '编辑分类'
  if (form.parentId) return '添加子分类'
  return '添加顶级分类'
})

const fetchCategories = async () => {
  try {
    loading.value = true
    categoryTree.value = await getCategoryTree()
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCategories()
})

const openDialog = (editData?: Category | null, parentData?: Category | null) => {
  // Reset form
  Object.assign(form, { id: undefined, name: '', parentId: 0, sort: 0 })

  if (editData) {
    // Editing existing category
    Object.assign(form, editData)
  } else if (parentData) {
    // Adding a child category
    form.parentId = parentData.id
  }
  // For new top-level category, parentId remains 0

  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateCategory(form.id!, form)
          ElMessage.success('更新成功')
        } else {
          await createCategory(form)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        fetchCategories() // Refresh tree
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      }
    }
  })
}

const handleDelete = async (data: Category) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${data.name}" 吗？如果它包含子分类，将一并删除。`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteCategory(data.id)
    ElMessage.success('删除成功')
    fetchCategories() // Refresh tree
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
